package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Transactional
@Service(interfaceClass = OrderService.class)
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired
    private MemberDao memberDao;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Order> page = orderDao.selectByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(), page.getResult());
    }

    //体检预约
    @Override
    public Result order(Map map) throws Exception {
        //1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
        String orderDate = (String) map.get("orderDate");//获取用户输入的预约日期
        //根据日期获取当天预约信息
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(DateUtils.parseString2Date(orderDate));
        if (orderSetting == null) {
            //用户选择的预约日期没有进行过预约设置,不能预约
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
        int number = orderSetting.getNumber();//获取当天可预约人数
        int reservations = orderSetting.getReservations();//获取当天以预约人数
        if (number <= reservations) {
            //当天已经预约满了,不能预约
            return new Result(false, MessageConstant.ORDER_FULL);
        }
        //3、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
        String telephone = (String) map.get("telephone");//获取用户页面输入的手机号
        //根据手机号获取用户信息
        Member member = memberDao.findByTelephone(telephone);
        //判断是否查询到用户信息,有则说明用户预约过,再进一步判断
        if (member != null) {
            Integer id = member.getId();//用户id
            Date order_date = DateUtils.parseString2Date(orderDate);//用户选择的预约日期
            String setmealId = (String) map.get("setmealId");//用户选择的套餐ID
            //将三个数据封装到Order
            Order order = new Order(id, order_date, Integer.parseInt(setmealId));
            //根据条件进行查询
            List<Order> list = orderDao.findByCondition(order);
            if (list != null && list.size() > 0) {
                //用户查询到数据说明当天这个用户已经预约过该套餐
                return new Result(false, MessageConstant.HAS_ORDERED);
            }
        } else {
            //4、检查当前用户是否为会员,如果不是会员则自动完成注册并进行预约
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            memberDao.add(member);//自动完成会员注册
        }
        //5、预约成功，更新当日的已预约人数
        Order order = new Order();
        order.setMemberId(member.getId());//设置会员ID
        order.setOrderDate(DateUtils.parseString2Date(orderDate));//预约日期
        order.setOrderType((String) map.get("orderType"));//预约类型
        order.setOrderStatus(Order.ORDERSTATUS_NO);//到诊状态(未到诊)
        order.setSetmealId(Integer.parseInt((String) map.get("setmealId")));//套餐ID (类型转换:Object->String->Integer)
        orderDao.add(order);//自动完成预约订单
        //设置已预约人数+1
        orderSetting.setReservations(orderSetting.getReservations() + 1);
        //更新预约列表数据库信息
        orderSettingDao.editReservationsByOrderDate(orderSetting);
        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());
    }

    @Override
    public Map findById(Integer id) throws Exception {
        Map map = orderDao.findById4Detail(id);
        if (map != null) {
            Date orderDate = (Date) map.get("orderDate");
            String order_date = DateUtils.parseDate2String(orderDate);
            map.put("orderDate", order_date);
        }
        return map;
    }

    /*
    age: "18"                              年龄                  无
    idCard: "43211212121212"               身份证                member
    marry: "1"                             婚姻                  无
    name: "张三"                           姓名                  member
    orderDate: "2020-08-18"                预约日期              order
    setmealId: [12, 13, 14]                套餐名称              setmeal
    sex: "1"                               性别                   member
    telephone: "17673099413"               手机                  member
                                           预约类型                 order
                                           预约状态                 order

                                            map.put("orderType", Order.ORDERTYPE_WEIXIN);//设置预约类型,当前方法预约的都是微信预约
                                            order.setOrderStatus(Order.ORDERSTATUS_NO);//到诊状态(未到诊)

     */
    //后台添加预约列表
    @Override
    public Result add(Map map) throws Exception {
        //1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
        String orderDate = (String) map.get("orderDate");//获取用户输入的预约日期
        //根据日期获取当天预约信息
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(DateUtils.parseString2Date(orderDate));
        if (orderSetting == null) {
            //用户选择的预约日期没有进行过预约设置,不能预约
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
        int number = orderSetting.getNumber();//获取当天可预约人数
        int reservations = orderSetting.getReservations();//获取当天以预约人数
        if (number <= reservations) {
            //当天已经预约满了,不能预约
            return new Result(false, MessageConstant.ORDER_FULL);
        }

        //3、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
        String telephone = (String) map.get("telephone");//获取用户页面输入的手机号
        //根据手机号获取用户信息
        Member member = memberDao.findByTelephone(telephone);
        //判断是否查询到用户信息,有则说明用户预约过,再进一步判断

//        String s = (String) map.get("setmealId");
        String s = map.get("setmealId").toString();
        String substring = s.substring(1, s.length() - 1);
        String[] split = substring.split(",");
        List<Integer> setmealIds = new ArrayList<>();
        for (String s1 : split) {
            String trim = s1.trim();
            Integer setmealId = Integer.parseInt(trim);
            setmealIds.add(setmealId);
        }
        if (member != null) {
            //将三个数据封装到Order
            for (Integer setmealId : setmealIds) {
                Integer id = member.getId();//用户id
                Date order_date = DateUtils.parseString2Date(orderDate);//用户选择的预约日期
                Order order = new Order(id, order_date, setmealId);
                //根据条件进行查询
                List<Order> list = orderDao.findByCondition(order);
                if (list != null && list.size() > 0) {
                    //用户查询到数据说明当天这个用户已经预约过该套餐
                    return new Result(false, MessageConstant.HAS_ORDERED);
                }
            }
        } else {
            //4、检查当前用户是否为会员,如果不是会员则自动完成注册并进行预约
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            memberDao.add(member);//自动完成会员注册
        }
        //5、预约成功，更新当日的已预约人数
        Order order = new Order();
        order.setMemberId(member.getId());//设置会员ID
        order.setOrderDate(DateUtils.parseString2Date(orderDate));//预约日期
        order.setOrderType(Order.ORDERTYPE_WEIXIN);//预约类型
//        order.setOrderStatus(Order.ORDERSTATUS_NO);//到诊状态(未到诊)
//        order.setSetmealId(Integer.parseInt((String) map.get("setmealId")));//套餐ID (类型转换:Object->String->Integer)
        for (Integer setmealId : setmealIds) {
            order.setSetmealId(setmealId);
            orderDao.add(order);//自动完成预约订单
        }
        //设置已预约人数
        orderSetting.setReservations(orderSetting.getReservations() + setmealIds.size());
        //更新预约列表数据库信息
        orderSettingDao.editReservationsByOrderDate(orderSetting);
        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());
    }

    @Override
    public Result confirmAppointment(Integer id) {
        String orderStatus = orderDao.findOrderTypeById(id);
        if ("未到诊".equals(orderStatus)) {
            return new Result(false, "你已经预约了此套餐,请勿重复预约");
        } else if ("已到诊".equals(orderStatus)) {
            return new Result(false, "你在逗我吗?");
        } else if (orderStatus == null|| orderStatus == "") {
            orderDao.updateOrderInOrderStatus(id);
            return new Result(true, "预约成功,请及时到诊");
        } else {
            return new Result(false, "未知错误,预约失败!!");
        }
    }

    @Override
    public void cancelReservation(Integer id) {
        orderDao.deleteOrderById(id);
    }

    @Override
    public void batchCancelReservation(Integer[] orderIds) {
        for (Integer id : orderIds) {
            orderDao.deleteOrderById(id);
        }
    }
}
